<!-- 搜索项目 -->
<template>
  <view>
    <view @click="onClick">
      <u--input
        :placeholder="placeholder"
        :placeholderClass="placeholderClass"
        :placeholderStyle="placeholderStyle"
        :inputAlign="inputAlign"
        :fontSize="fontSize"
        :color="color"
        :prefixIcon="prefixIcon"
        :prefixIconStyle="prefixIconStyle"
        :suffixIcon="suffixIcon"
        :suffixIconStyle="suffixIconStyle"
        :border="border"
        :shape="shape"
        :customStyle="customStyle"
        v-model="title"
        disabled
        :disabledColor="disabledColor"
      ></u--input>
    </view>
    <u-popup class="form-popup" mode="right" :show="showPopup" @close="close" @open="open">
      <!-- <u-loading-page color="#666" v-if="loading"></u-loading-page> -->
      <view>
        <u-navbar :title="placeholder" @leftClick="close" style="color: blue;" :safeAreaInsetTop="false"></u-navbar>
        <view :style="'height:' + getSafeAreaTop() + 'px'" style="color: red; width: 750rpx;"></view>
        <common-search
          v-show="useSearch"
          class="search"
          v-model="searchKey"
          :screenShow="screenShow"
          @screenclick="screenclick"
          @searchMsg="searchMsg"
          :placeholder="searchPlaceholder"
        ></common-search>
        <scroll-view scroll-y class="popup-list-page" :style="'height: ' + getScorollHeight() + 'px;'" @scrolltolower="loadData">
          <template v-if="isData">
            <view class="page">
              <view class="list-item" v-for="(item, index) in entities" :key="index" @click="onChecker(item, index)">
                <slot :item="item" />
                <view class="icon" v-show="item.isChecker">
                  <u-icon name="checkbox-mark" color="#2979ff" size="22"></u-icon>
                </view>
              </view>
              <!-- 加载更多显示 -->
              <view><u-loadmore :status="loadStatus" /></view>
            </view>
          </template>
          <view v-else>
            <u-empty mode="data" icon="/static/empty/data.png"></u-empty>
          </view>
          <view style="height: 160rpx"></view>
          <view class="btn">
            <u-button text="确定" type="primary" @click="onConfirm"></u-button>
          </view>
        </scroll-view>
        <u-toast ref="uToast"></u-toast>
      </view>
    </u-popup>
  </view>
</template>

<script>
import CommonSearch from '../../components/CommonSearch.vue'

export default {
  name: 'HSelectInputPopup',
  data() {
    return {
      loading: false,
      showPopup: false,
      title: '', // 选中的标题名称
      showNotify: true, // 消息提示
      checkId: '', // 选中的id
      checkItem: [],
      page: {
        pageNo: 1,
        pageSize: 10,
      },
      entities: [], // 列表
      isData: true, // 判断是否有数据  true 代表有 false 代表无
      loadStatus: 'loadmore', // 通过status设置组件的状态，加载前值为loadmore，加载中为loading，没有数据为nomore
      oldIndex: null, // 存储列表之前被选中的数据
      screenShow: false, // 筛选弹窗
      // 传的参数
      queryParam: this.params,
    }
  },
  components: {
    CommonSearch,
  },
  model: {
    prop: 'value',
    event: 'input',
  },
  props: {
    valKey: {
      type: [String, Number],
      default: 'id',
    },
    // 是否需要判断
    isJudge: {
      type: Boolean,
      default: false,
    },
    useSearch: {
      type: Boolean,
      default: true,
    },
    // 是否从 result records 中获取数据
    records: {
      type: Boolean,
      default: true,
    },
    searchPlaceholder: {
      type: String,
      default: '请输入',
    },
    isMulti: {
      type: Boolean,
      default: false,
    },
    // 编号（不知道啥玩意后台没有备注）
    signUnit: {
      type: [String, Number],
      default: '',
    },
    // 借款所属团队
    teamName2: {
      type: [String, Number],
      default: '',
    },
    // 对象字段
    objectField: {
      type: [String],
      default: 'basicForm.yzdw',
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false,
    },
    // 选中的值
    value: {
      type: [String, Number, Array],
      default: '',
    },
    // 输入框为空时的占位符
    placeholder: {
      type: [String, Number],
      default: '请选择',
    },
    // 指定placeholder的样式类，注意页面或组件的style中写了scoped时，需要在类名前写/deep/
    placeholderClass: {
      type: [String],
      default: '',
    },
    // 指定placeholder的样式，字符串/对象形式，如"color: red;"
    placeholderStyle: {
      type: [String, Object],
      default: 'color: #C0C4CC'
    },
    // 输入框内容对齐方式 - left | center | right
    inputAlign: {
      type: [String],
      default: 'left',
    },
    // 输入框字体的大小
    fontSize: {
      type: [String, Number],
      default: '15px',
    },
    // 输入框字体颜色
    color: {
      type: [String],
      default: '#303133',
    },
    // 输入框前置图标
    prefixIcon: {
      type: [String],
      default: '',
    },
    // 前置图标样式，对象或字符串
    prefixIconStyle: {
      type: [String, Object],
      default: '',
    },
    // 输入框前置图标
    suffixIcon: {
      type: [String],
      default: '',
    },
    // 前置图标样式，对象或字符串
    suffixIconStyle: {
      type: [String, Object],
      default: '',
    },
    // 边框类型，surround-四周边框，bottom-底部边框，none-无边框
    border: {
      type: [String],
      default: 'surround',
    },
    // 输入框形状，circle-圆形，square-方形
    shape: {
      type: [String],
      default: 'square',
    },
    customStyle: {
      type: [Object],
      default: () => {},
    },
    params: {
      type: Object,
      default: () => {},
    },
    keywords: {
      type: String,
      default: '',
    },
    getList: {
      type: Function,
      default: () => {},
    },
    isUnique: {
      type: Boolean,
      default: false,
    },
		// 第一次是否请求
		isRequest: {
      type: Boolean,
      default: true,
    },
		recordList: {
			type: Array,
			default: () => [],
		},
		// 是否直接携帶列表数据过来
		isrecordList: {
			type: Boolean,
			default: false,
		}
  },
  watch: {
    // 监听value是否有值
    value: {
      handler(val, oldVal) {
        this.checkId = val // 初始化值id
        if (val) {
          this.getItemDetail(val)
        } else {
          this.title = ''
					this.checkItem = [] // 清空选中的数据
        }
      },
      deep: true,
      immediate: true,
    },
    params: {
      handler(val, oldVal) {
        this.queryParam = val
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    // 当是disabled为true改变禁用的颜色
    disabledColor() {
      return this.disabled ? '#f5f7fa' : '#FFFFFF'
    },
    searchKey: {
      get() {
        return this.keywords
      },
      set(val) {
        return this.$emit('update:keywords', val)
      },
    },
  },
  methods: {
    // 获取列表
    async getEntities() {
			if (!this.isRequest) {
				this.loadStatus = 'nomore'
				return false
			}
      this.loadStatus = 'loading' // 加载中
      try {
				var data = []
				var res = {}
				if (this.isrecordList) {
					data = JSON.parse(JSON.stringify(this.recordList))
					res.success = true
				} else {
					res = await this.getList(this.queryParam)
					data = this.records ? res.result.records : res.result
				}
        if (res.success) {
          // 是否数据去重
          if (this.isUnique) {
            let projectLeadingTemp = []
            data.forEach((item) => {
              if (item.projectLeading) {
                projectLeadingTemp.push({
                  id: item.projectLeading,
                  name: item.projLeadName,
                })
              }
            })
            data = Array.from(new Set(projectLeadingTemp.map((item) => JSON.stringify(item)))).map((item) => JSON.parse(item))
          }
          // 判断首次加载是否有数据
          if (this.queryParam.pageNo == 1) {
            if (data && data.length) {
              this.isData = true
            } else {
              this.isData = false
            }
          }
          if (data && data.length) {
            if (data.length >= 10) {
              this.loadStatus = 'loadmore'
            } else {
              this.loadStatus = 'nomore'
            }

            // 处理数据
						this.oldIndex = 0
            var empIdArr = this.checkId ? this.checkId.split(',') : []
            if (empIdArr.length == 1) {
              data.map((value, index) => {
                // 是否选中数据
                if (this.checkId == value[this.valKey]) {
                  // this.checkItem.push(value)
                  value.isChecker = true
                  // this.oldIndex = index // 当单选的时候
                } else {
                  value.isChecker = false
                }
                return value
              })
            } else {
              data.map((value, index) => {
                // 是否选中数据
                value.isChecker = false
                empIdArr.map((item, ind) => {
                  if (item == value[this.valKey]) {
                    value.isChecker = true
                    // this.checkItem.push(value)
                    // this.oldIndex = index // 当单选的时候
                  }
                })

                return value
              })
            }
          } else {
            this.loadStatus = 'nomore'
          }
          if (this.queryParam.pageNo == 1) {
            this.entities = data
          } else {
            this.entities = this.entities.concat(data)
          }
					if (this.entities && this.entities.length && !this.isMulti) {
						const oldIndex =	this.entities.findIndex(item => item.isChecker)
						if (oldIndex == -1) {
							this.oldIndex = 0
						} else {
							this.oldIndex = oldIndex
						}
					}
        }
      } catch (error) {
        console.error('出错了', error)
      } finally {
        this.loading = false
      }
    },
    loadData() {
      if (this.loadStatus == 'nomore' || this.loadStatus == 'loading') return false
      this.queryParam.pageNo++
      this.getEntities()
    },
    // 获取详情
    getItemDetail(id) {
      this.$emit('getDetail', id)
    },

    // 获取safeArea
    getSafeAreaTop() {
      var top = 44
      return top
    },
    // 获取safeArea
    getScorollHeight() {
      let height = uni.getStorageSync('getSystemInfo').screenHeight - (uni.getStorageSync('getSystemInfo')?.safeArea?.top || 0) - (uni.getStorageSync('getSystemInfo')?.statusBarHeight || 0) - 44 - 32
      return height
    },
    // 点击选中取消选中
    onChecker(item, index) {
      if (this.loadStatus === 'loading') {
        return
      }
      // 多选
      if (this.isMulti) {
        item.isChecker = !item.isChecker
        this.updateTitle()
        this.onIsChecker(item)
        return
      }

      // 单选
      item.isChecker = !item.isChecker
      if (this.oldIndex !== null && this.oldIndex !== index) {
        this.entities[this.oldIndex].isChecker = false
        this.checkId = item[this.valKey]
        this.checkItem = [item]
      } else {
        this.checkId = ''
        this.checkItem = []
      }
      this.updateTitle()
      this.oldIndex = index

      this.$emit('choosed', item)
    },

    // 用于判断修改当前的id值
    onIsChecker(item) {
      // 判断当前值是否被选中
      if (item.isChecker) {
        // 被选中,直接拼接id值
        if (this.checkId) {
          this.checkId = this.checkId + ',' + item[this.valKey]
        } else {
          this.checkId = item[this.valKey]
        }
        this.checkItem.push(item)
      } else {
        // 当被取消选中,则在id值中去除此id值
        var empIdArr = this.checkId.split(',')
        if (empIdArr.length == 1) {
          // 当id值只有一个时则直接清除
          this.checkId = ''
          this.checkItem = []
        } else {
          // 当id值是多个的时候
          empIdArr.map((val, ind) => {
            if (val == item[this.valKey]) {
              empIdArr.splice(ind, 1) // 删除当前的id值
            }
          })
          this.checkId = empIdArr.toString()
          this.checkItem.map((val, ind) => {
            if (val[this.valKey] == item[this.valKey]) {
              this.checkItem.splice(ind, 1) // 删除当前的id值
            }
          })
        }
      }
    },

    updateTitle() {
      const hasCheck = this.entities.some((i) => i.isChecker)
      if (!hasCheck) this.title = ''
    },
    onClick() {
      if (this.disabled) return
      if (this.isJudge) {
        this.$emit('onJudge')
        return false
      }
      this.showPopup = true
    },
    // 输入内容
    searchMsg(keywords) {
      this.page.pageNo = 1 // 页数归1
      this.dataList = [] // 清空列表
      this.$nextTick(() => {
        this.getEntities() // 获取列表
      })
    },
    // 点击筛选
    screenclick() {
      this.screenShow = !this.screenShow
    },
    onConfirm() {
      if (this.isMulti) {
        // const items = this.entities.filter((i) => i.isChecker)
        // const data = items.map((i) => i?.[this.valKey])
        this.$emit('input', this.checkId)
        if (this.checkId && this.checkId.length) {
          this.getItemDetail(this.checkId)
        }
        if (this.checkId !== this.value) {
          this.$emit('change', this.checkItem)
          this.$emit('realChange', this.checkItem)
        }
				
        //全不选
        if(!this.checkId && this.isUnique) {
          this.getItemDetail(this.checkItem)
        }
				this.$emit('back', this.checkItem)
      } else {
        const item = this.entities.find((i) => i.isChecker)
        this.$emit('input', item?.[this.valKey] || '')
        if (item && item.id) {
          this.getItemDetail(item[this.valKey])
        }
        if (this.value !== item?.[this.valKey]) {
          this.$emit('change', item)
          this.$emit('realChange', item)
        }
				this.$emit('back', item)
      }
      this.showPopup = false
      this.$emit('update:keywords', '')
    },
    open() {
			this.queryParam.pageNo = 1 // 每次打开的时候都是在第一页
			this.dataList = [] // 清空列表
      this.$nextTick(() => {
				this.getEntities() // 获取列表
			})
    },
    close() {
      this.showPopup = false
      this.$emit('update:keywords', '')
    },
  },
}
</script>

<style lang="scss" scoped>
.page {
  padding: 0 20rpx 20rpx 20rpx;
}
.list-item {
  border-radius: 10rpx;
  box-shadow: 0px 4px 20px 0px rgba(0, 0, 0, 0.1);
  padding: 12rpx 20rpx 20rpx 20rpx;
  background: #ffffff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 20rpx;
}
// 按钮
.btn {
  position: fixed;
  bottom: 20rpx;
  width: 100%;
  padding: 0 10px;
}
</style>
